package cn.laixueit.source.service;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * @author duxiang
 * @date 2024/3/8 16:24
 */

public abstract class TreeService<T>{

    public List<Tree<String>> constructTree(List<T> dataList) {
        //1.获取所有资料分类

        //2.配置
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id");                              //默认id，可以不设置
        config.setParentIdKey("pid");                       //父id
        config.setNameKey("name");              //分类名称
        config.setDeep(3);                                  //最大递归深度
        config.setChildrenKey("childrenList");              //孩子节点
        config.setWeightKey("sort");                        //排序字段

        //3.转树
        List<Tree<String>> treeList = TreeUtil.build(dataList, "0", config, ((object, treeNode) -> {
            treeNode.putExtra("id", ReflectUtil.getField(object.getClass(),"id"));
            treeNode.putExtra("pid",ReflectUtil.getField(object.getClass(),"pid"));
            treeNode.putExtra("name", ReflectUtil.getField(object.getClass(),"name"));
            treeNode.putExtra("level",  ReflectUtil.getField(object.getClass(),"level"));
            treeNode.putExtra("sort",  ReflectUtil.getField(object.getClass(),"sort"));
            //扩展属性...
        }));

        return treeList;
    }
}
